#!/bin/sh

red="\033[1;31m"
green="\033[1;32m"
blue="\033[1;34m"
cr="\033[0m"

URL="https://www.twitch.tv"
STREAMERS_FILE_PATH="$HOME/.config/terwitch/streamers_file"
MODE=0
ARGS=0

die() {
	printf "$red%s$cr\n" "$*"
	exit 1
}

check_deps() {
	while IFS= read -r dep; do
		[ "$(command -v "$dep")" = '' ] && die "$dep not found, it is required for Terwitch to work. Check the README for details on installing dependencies."
	done <<-EOF
		twt
		mpv
		yt-dlp
		twiins
	EOF
}

print_usage() {
	while IFS= read -r line; do
		printf "%s\n" "$line"
	done <<-EOF
		Usage:
		   terwitch <flags> <args>
		Flags:
		  -c             Read streamers_file and check which streamers are online
		  -C <streamer>  Connect to streamer's chat only
		  -v <streamer>  View streamer's stream only
		  -V <streamer>  View streamer's chat and connect to streamer's chat
		  -a <streamer>  Add streamer to streamers_file
		  -r <streamer>  Remove streamer from streamers_file

		Launch without flags to print this message again
	EOF
}

check_streamers() {
	[ ! -e "$STREAMERS_FILE_PATH" ] && die "Streamers file no found. Please create one at $STREAMERS_FILE_PATH"

	online=""
	while read -r streamer; do
		isLive="$(twiins check-live "$streamer" -p)"
		if [ "$(printf "%s" "$isLive" | grep "True")" = "True" ]; then
			online="${online} $streamer" && printf "%s is$green ONLINE $cr\n" "$streamer"
		else
			printf "%s is$red OFFLINE $cr\n" "$streamer"
		fi
	done <"$STREAMERS_FILE_PATH"

	[ "$online" != "" ] && printf "\nOnline streamers NOW:\n%s\n" "$online" || printf "No one is online now :(\n"
}

view() {
	setsid -f mpv "$URL/$*" --really-quiet >/dev/null 2>&1
}

chat() {
	twt -c "$*"
}

add_streamer() {
	new_streamer="$*"
	[ "$(grep -cm 1 "^$new_streamer$" "$STREAMERS_FILE_PATH")" -eq 1 ] && die "Streamer $new_streamer already in streamers_file"
	printf "%s\n" "$new_streamer" >>"$STREAMERS_FILE_PATH"
	printf "Streamer $blue%s$cr added to streamers_file\n" "$new_streamer"
}

remove_streamer() {
	streamer="$*"
	[ "$(grep -cm 1 "^$streamer$" "$STREAMERS_FILE_PATH")" -eq 0 ] && die "Streamer $streamer not found in streamers_file"
	sed -i "/^$streamer$/d" "$STREAMERS_FILE_PATH" && printf "Successfully removed $blue%s$cr from streamers_file\n" "$streamer"
}

# === INIT ===

check_deps

while getopts 'cv:V:a:r:C:' OPT; do
	case $OPT in
	c)
		MODE=1
		;;
	v)
		MODE=2
		ARGS="$OPTARG"
		;;
	V)
		MODE=3
		ARGS="$OPTARG"
		;;
	a)
		MODE=4
		ARGS="$OPTARG"
		;;
	r)
		MODE=5
		ARGS="$OPTARG"
		;;
	C)
		MODE=6
		ARGS="$OPTARG"
		;;
	?) ;;
	esac
done
shift "$((OPTIND - 1))"

case $MODE in
0)
	print_usage
	;;
1)
	check_streamers
	;;
2)
	view "$ARGS"
	;;
3)
	view "$ARGS"
	chat "$ARGS"
	;;
4)
	add_streamer "$ARGS"
	;;
5)
	remove_streamer "$ARGS"
	;;
6)
	chat "$ARGS"
	;;
?)
	echo "ERROR" && exit 1
	;;
esac
